package soen343.application;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FrontController() {
        super();
    }

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	private Class<?> getCommandClass(String commandName) throws Exception {  
		String cmdClassName = "soen343.application." + commandName + "Command";
		try {
			Class<?> result = Class.forName(cmdClassName);
			return result;
		} catch(ClassNotFoundException e) {
			throw new Exception("Unknown command: " + cmdClassName);
		}
	}
	
	private FrontCommand getCommand(String commandName)
			throws Exception, InstantiationException, IllegalAccessException {
		return (FrontCommand) getCommandClass(commandName).newInstance();
	}
	
	protected void processRequest( 
			HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException 
	{

		FrontCommand fc = null;
		try {
			fc = getCommand(request.getParameter("command"));
			fc.init( getServletContext() );
			fc.processRequest( request, response );
		} catch (Exception e) {
			//e.printStackTrace(response.getWriter());
			request.setAttribute("errorMessage", e.toString());
			forward("/Error.jsp", request, response);
		}
	}
	
	private void forward(
			String target, 
			HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException 
	{
		getServletContext().getRequestDispatcher(target).forward(request, response);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(
			HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(
			HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
